package com.wd.mqtt.v2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.kqueue.KQueueEventLoopGroup;
import io.netty.channel.kqueue.KQueueServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.mqtt.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.ChannelHandlerContext;

public  class OptimizedMqttNettyServer {

    private static final int PORT = 1883;

    public static void main(String[] args) throws InterruptedException {
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        int bossGroupThreads = Math.max(1, availableProcessors / 2);
        int workerGroupThreads = availableProcessors * 4;

        EventLoopGroup bossGroup;
        EventLoopGroup workerGroup;

        // 使用 Epoll 或 KQueue 替代 Nio
        if (isLinux()) {
            bossGroup = new EpollEventLoopGroup(bossGroupThreads);
            workerGroup = new EpollEventLoopGroup(workerGroupThreads);
        } else if (isMac()) {
            bossGroup = new KQueueEventLoopGroup(bossGroupThreads);
            workerGroup = new KQueueEventLoopGroup(workerGroupThreads);
        } else {
            bossGroup = new NioEventLoopGroup(bossGroupThreads);
            workerGroup = new NioEventLoopGroup(workerGroupThreads);
        }

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(isLinux() ? EpollServerSocketChannel.class : (isMac() ? KQueueServerSocketChannel.class : NioServerSocketChannel.class))
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.SO_RCVBUF, 1024*8)
                    .childOption(ChannelOption.SO_SNDBUF, 1024*8)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast("mqttDecoder", new MqttDecoder());
                            ch.pipeline().addLast("mqttEncoder", MqttEncoder.INSTANCE);
                            ch.pipeline().addLast("mqttHandler", new MqttServerHandler());
                        }
                    });

            ChannelFuture f = b.bind(PORT).sync();
            System.out.println("MQTT server started on port " + PORT);
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    static class MqttServerHandler extends SimpleChannelInboundHandler<MqttMessage> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, MqttMessage msg) {
            if (msg.fixedHeader().messageType() == MqttMessageType.CONNECT) {
                handleConnect(ctx, (MqttConnectMessage) msg);
            }
            if (msg.fixedHeader().messageType() == MqttMessageType.PINGREQ) {
                handlePINGREQ(ctx, msg);
            }
        }

        private void handlePINGREQ(ChannelHandlerContext ctx, MqttMessage msg){
            MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PINGRESP, false, MqttQoS.AT_MOST_ONCE, false, 0);
            MqttMessage mqttMessageBack = new MqttMessage(fixedHeader);

            ctx.writeAndFlush(mqttMessageBack);
        }

        private void handleConnect(ChannelHandlerContext ctx, MqttConnectMessage msg) {
//            System.out.println("Received MQTT CONNECT message");

//            MqttFixedHeader connackFixedHeader = new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_LEAST_ONCE, false, 0);
            MqttMessage connackMessage = MqttMessageBuilders.connAck()
                    .returnCode(MqttConnectReturnCode.CONNECTION_ACCEPTED)
                    .sessionPresent(false)
                    .build();

            ctx.writeAndFlush(connackMessage);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    }

    private static boolean isLinux() {
        return System.getProperty("os.name").toLowerCase().contains("linux");
    }

    private static boolean isMac() {
        return System.getProperty("os.name").toLowerCase().contains("mac");
    }
}
